package com.miao.websecurity.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.miao.websecurity.entity.Admin;
import com.miao.websecurity.entity.SysRole;
import com.miao.websecurity.service.AdminService;
import com.miao.websecurity.service.RoleAdminService;

import lombok.extern.slf4j.Slf4j;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author MiaoWenqing
 * @description: TODO
 * @date 2021/1/16 19:28
 */
@Service(value = "myUserDetailsService")
@Slf4j
public class AuthUserDetailServiceImpl  implements UserDetailsService {

    @Resource
    private AdminService adminService;

    @Resource
    private RoleAdminService roleAdminService;

    @Resource(name = "myPasswordEncoder")
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String adminTel) throws UsernameNotFoundException {

        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        adminQueryWrapper.eq("admin_tel",adminTel);
        Admin admin = adminService.getOne(adminQueryWrapper);

        if (null==admin){
           throw new UsernameNotFoundException("账号不存在");
        }else {
            admin.setLastLoginTime(new Date());
            adminService.saveOrUpdate(admin);
            List<SysRole> adminRoleById = this.roleAdminService.getAdminRoleById(admin.getAdminId());
            ArrayList<String> strings = new ArrayList<>();
            adminRoleById.forEach(v->{
                log.info("角色信息[{}]",v.getRoleName());
                strings.add(v.getRoleName());
            });

            ArrayList<SimpleGrantedAuthority> roles = new ArrayList<>();
            for (String s : strings) {
                roles.add(new SimpleGrantedAuthority(s));
            }
            return new User( String.valueOf(admin.getAdminId()),admin.getAdminPasswd(),roles);
        }
    }
}
